package zpx.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import zpx.dao.ComAttachmentDao;
import zpx.iservice.IComAttachmentService;
import zpx.model.ComAttachment;
import zpx.model.User;
import zpx.util.Constants;



/**
  �����߼������ӿ�ʵ����
 */

@Service("comAttachmentService")
public class ComAttachmentService  implements IComAttachmentService {

    
    /** ������ݿ����DAO */
    private ComAttachmentDao comAttachmentDao;
    
    /**
     * ע�븽����ݿ����DAO
     */
    @Autowired
    public void setComAttachmentDao(ComAttachmentDao comAttachmentDao) {
        this.comAttachmentDao = comAttachmentDao;
    }
    
    /**
     * ��ݶ�Ӧ�����¼�����ʶ������������
     * 
     * @param recordId ��Ӧ�����¼�����ʶ
     * @return �����б�
     */
    @Override
    public List<ComAttachment> getAttachments(String recordId) {
        return comAttachmentDao.getAttachments(recordId);
    }
    
    
    /**
     * ���������ѯ
     * @param searchMap
     * @return
     */
    public List<ComAttachment> getAttachmentsLst(Map<String, String> searchMap){
        return comAttachmentDao.getAttachmentsLst(searchMap);
    }
    
    /**
     * ����������ȡ
     * 
     * @param attaId �����ļ���ʶ
     * @return ����
     */
    @Override
    public ComAttachment getAttachment(String attaId) {
        return comAttachmentDao.getAttachment(attaId);
    }
    
    /**
     * ����������������
     * 
     * @param attachment ��������
     * @return ��������
     */
    @Override
    public ComAttachment saveOrUpdateAttachment(ComAttachment attachment) {
        return comAttachmentDao.saveOrUpdateAttachment(attachment);
    }
    
    /**
     * �ƶ��ϴ�����������Ŀ¼�������ش��ĸ�������
     * 
     * @param uploadFile ��������ʱ�ļ�
     * @param fileName �ļ����(����չ��)
     * @param recordId ��Ӧ�����¼�����ʶ
     * 
     * @return ��������
     */
    @Override
    public ComAttachment moveAttachment(File uploadFile, String fileName, String recordId) {
    	ComAttachment attachment = new ComAttachment();
        // ��ɽ�Ҫ�����ļ���Ŀ¼
        SimpleDateFormat dt = new SimpleDateFormat("yyyy-MMdd");
        String filePath = dt.format(new Date());
        filePath = filePath.substring(0, 4) + Constants.FILE_SEP + filePath.substring(5, 9);
        
        // ��Ŀ¼�������ǽ�����Ŀ¼
        File fileDir = new File(Constants.ATTR_PATH + Constants.FILE_SEP + filePath);
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        
        // �ƶ����ļ�������Ŀ¼
        File newFile = new File(Constants.ATTR_PATH + Constants.FILE_SEP + filePath + Constants.FILE_SEP + uploadFile.getName());
        // uploadFile.renameTo(newFile);
        
        moveFile(uploadFile, newFile);
        
        // �趨�ļ�����ʾ���
        attachment.setAttaName(fileName);
        // �趨�ļ���������ʶ
        attachment.setRecordId(recordId);
        // �趨���ļ��ı���·��
        attachment.setAttaPath(filePath + Constants.FILE_SEP + uploadFile.getName());
        
        return attachment;
    }
    
    /**
     * ���� ����ļ���ɾ��
     * 
     * @param attachment ��Ҫ��ɾ��ĸ�������
     * @return ����
     */
    public ComAttachment todeleteAttachmentFile(ComAttachment attachment) {
        // ������ת�Ƶ�ɾ��Ŀ¼���ļ�
        File delFile = new File(Constants.ATTR_PATH + Constants.FILE_SEP + attachment.getAttaPath());
        // ���ݵ��ļ�
        File newFile = new File(Constants.ATTR_PATH + Constants.FILE_SEP + Constants.DEL_PATH + Constants.FILE_SEP
                + attachment.getAttaPath());
        // ��ɱ��ݵ�Ŀ¼
        File dir = new File(newFile.getParent());
        if (!dir.exists()) {
            dir.mkdirs();
        }
        // ���ļ�ת���������ļ�����
        // delFile.renameTo(newFile);
        moveFile(delFile, newFile);
        
        // �趨���ݵ�·��
        attachment.setAttaPath(Constants.DEL_PATH + Constants.FILE_SEP + attachment.getAttaPath());
        
        return attachment;
    }
    
    /**
     * ɾ���
     * 
     * @param attaId �����ļ���ʶ
     * @return ��������
     */
    @Override
    public void deleteAttachment(String attaId) {
        comAttachmentDao.deleteAttachment(attaId);
    }
    
    /**
     * ���渽��(������)
     * 
     * @param fileNames �������jQuery�ϴ��Զ����(��ʽ:2298sd-2ds-d.png,iu98-23d2-22.txt)
     * @param filePaths ����·��(��ʽ:/��Ŀ��/uploads//xxxx.png,/��Ŀ��/uploads//xxx.txt)
     * @param recordId ��Ӧ�����¼�����ʶ
     */
    @Override
    public void saveComAttachment(String fileNames, String filePaths, String recordId,User loginUser) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("fileNames", fileNames);
        map.put("filePaths", filePaths);
        map.put("recordId", recordId);
        map.put("loginUser", loginUser);
        map.put("group", "");
        toSaveComAttchment(map);
    }
    
    /**
     * ���渽��(���������)(������)
     * 
     * @param fileNames �������jQuery�ϴ��Զ����(��ʽ:2298sd-2ds-d.png,iu98-23d2-22.txt)
     * @param filePaths ����·��(��ʽ:/��Ŀ��/uploads//xxxx.png,/��Ŀ��/uploads//xxx.txt)
     * @param recordId ��Ӧ�����¼�����ʶ
     * @param group �����ļ���(��Щ�����ļ���ͬʱ�ϴ�,�������һ�ű��д��������ط��ϴ�����)
     */
    @Override
    public void saveComAttachmentByGroup(String fileNames, String filePaths, String recordId, String group) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("fileNames", fileNames);
        map.put("filePaths", filePaths);
        map.put("recordId", recordId);
        map.put("group", group);
        toSaveComAttchment(map);
    }
    
    public void toSaveComAttchment(Map<String, Object> map) {
        // �������
        String filePaths = (String) map.get("filePaths");
        // ����·��
        String fileNames = (String) map.get("fileNames");
        User loginUser = (User) map.get("loginUser");
        // ������Ӧ�����¼�����ʶ
        String recordId = (String) map.get("recordId");
        if (filePaths != null && !"".equals(filePaths)) {
            String[] pathsArray = filePaths.split(",");
            String[] filesArray = fileNames.split(",");
            for (int i = 0; i < pathsArray.length; i++) {
                String path = pathsArray[i];
                String fileName = filesArray[i];
                if (path != null && !"".equals(path.trim()) && fileName != null && !"".equals(fileName.trim())) {
                    // ϵͳ·��
                    // String sysPath =
                    // getClass().getProtectionDomain().getCodeSource().getLocation()
                    // .getPath();
                    // ��ʱ�ļ�·��
                    // String upload = sysPath.substring(1, sysPath.indexOf("WEB-INF")) + "uploads"
                    // + File.separator + fileName;
                    
                    String upload = Constants.APP_PATH + File.separator + "uploads" + File.separator + fileName.trim();
                    
                    File uploadFile = new File(upload);
                    // �ļ��ϴ���
                    String name = path.substring(path.lastIndexOf("/")).substring(1);
                    // ��ȡ�ļ�
                    ComAttachment comAttachment = moveAttachment(uploadFile, name, recordId);
                    if (comAttachment != null) {
                        // ȡ�õ�¼�û���Ϣ
                       // Object obj = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
                        // ��¼�û���ʶ
                        String userID = loginUser.getId();
                       // HttpServletRequest hsq = (HttpServletRequest) req;
                		//User u = (User)hsq.getSession().getAttribute("loginUser");
                       /* if (obj instanceof SysUser) {
                            // ��¼�û���ʶ
                            userID = ((SysUser) obj).getPersonId();
                        }*/
                        
                        // ������
                        comAttachment.setCreatePerson(userID + "");
                        // ��ǰʱ��
                        Date tempDate = new Date();
                        // ����ʱ��
                        comAttachment.setCreateDate(tempDate);
                        // ״̬ 1��ʾ��
                        comAttachment.setAttaStatus("1");
                        // �ж��ϴ��ĸ��������Ƿ����
                        if (fileName.lastIndexOf(".") == -1) {
                            // ���ø�������Ϊ��
                            comAttachment.setAttaType("");
                        } else {
                            // ���ø�������
                            comAttachment.setAttaType(fileName.substring(fileName.lastIndexOf(".") + 1));
                        }
                        // ��Ӧ�����¼�����ʶ
                        comAttachment.setRecordId(recordId);
                        // ������
                        //comAttachment.setAttaGroupId(map.get("group"));
                        // ���渽����Ϣ
                        // saveOrUpdateAttachment(comAttachment);
                        comAttachmentDao.saveOrUpdateAttachment(comAttachment);
                        
                    }
                }
            }
        }
    }
    
    /**
     * ɾ���(������)
     * 
     * @param delComAttIds ������ʶ(��ʽ:��","���)
     */
    @Override
    public void deleteComAttachments(String delComAttIds, User loginUser) {
        removeComAttachments(delComAttIds, loginUser);
    }
    
    /**
     * 
     * @param recordId �����ļ���Ӧ���ʶ
     * @param group ���
     * @return �����б�
     */
    @Override
    public List<ComAttachment> getComAttachmentList(String recordId, String group) {
        return comAttachmentDao.getComAttachmentList(recordId, group);
    }
    
    private void moveFile(File sourceFile, File targetFile) {
        try {
            
            FileInputStream fis = new FileInputStream(sourceFile);
            FileOutputStream fos = new FileOutputStream(targetFile);
            try {
                byte[] buf = new byte[8192];
                do {
                    int rc = fis.read(buf);
                    if (rc == -1)
                        break;
                    fos.write(buf, 0, rc);
                    if (rc < buf.length)
                        break;
                } while (true);
            } finally {
                fis.close();
                fos.close();
            }
            sourceFile.delete();
        } catch (Exception e) {
            System.out.println("�ļ�����ʧ��!");
        }
        
    }
    
    /**
     * ���渽��
     * 
     * @param fileNames �������jQuery�ϴ��Զ����(��ʽ:2298sd-2ds-d.png,iu98-23d2-22.txt)
     * @param filePaths ����·��(��ʽ:/��Ŀ��/uploads//xxxx.png,/��Ŀ��/uploads//xxx.txt)
     * @param recordId ��Ӧ�����¼�����ʶ
     */
    @Override
    public void createComAttachment(String fileNames, String filePaths, String recordId) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("fileNames", fileNames);
        map.put("filePaths", filePaths);
        map.put("recordId", recordId);
        map.put("group", "");
        toSaveComAttchment(map);
    }
    
    /**
     * ɾ���
     * 
     * @param delComAttIds ������ʶ(��ʽ:��","���)
     */
    @Override
    public void removeComAttachments(String delComAttIds ,User loginUser) {
        // ����ֵ
        if (delComAttIds != null && !"".equals(delComAttIds.trim())) {
            // ������ʶ����
            String[] attaIdArray = delComAttIds.split(",");
            for (String attaId : attaIdArray) {
                if (attaId != null && !"".equals(attaId.trim())) {
                    // ��ݱ�ʶ��ø�����Ϣ
                	ComAttachment comAtta = getAttachment(attaId);
                    // ɾ���
                    comAtta = todeleteAttachmentFile(comAtta);
                    
                    // ȡ�õ�¼�û���Ϣ
                   // Object obj = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
                    // ��¼�û���ʶ
                    String userID =loginUser.getId();
                    //if (obj instanceof User) {
                        // ��¼�û���ʶ
                       // userID = ((User) obj).getId();
                    //}
                    // ���ø�����
                    comAtta.setUpdatePerson(userID + "");
                    // ��ǰʱ��
                    Date tempDate = new Date();
                    // ���ø���ʱ��
                    comAtta.setUpdateDate(tempDate);
                    // ����Ϊɾ��
                    comAtta.setAttaStatus("0");
                    // ���¸�����Ϣ
                    // saveOrUpdateAttachment(comAtta);
                    // ����ֵ
                    comAttachmentDao.saveOrUpdateAttachment(comAtta);
                }
            }
        }
    }
    
}